<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Sms;
use app\common\library\Wechat;
use app\common\model\Bank;
use app\common\model\FrozenLog;
use app\common\model\MoneyLog;
use app\common\model\order\Goods;
use app\common\model\order\goods\Log;
use app\common\model\order\Order;
use app\common\model\User as ModelUser;
use app\common\model\user\Info;
use app\common\model\user\Region;
use app\common\model\user\Withdrawal;
use fast\Random;
use think\Config;
use think\Db;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['mobilelogin', 'changemobile', 'miniLogin'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $userInfo = ModelUser::get($this->auth->id, ['referrer']);
        if (!$userInfo->qr_image && $userInfo->group_id > 0) {
            $wechat = new Wechat('wxMiniProgram');
            $scene = 'code=' . $userInfo->qr_code;
            $response = $wechat->app_code($scene, [
                'page' => 'pages/login/register',
                'width' => 600,
                'check_path' => false,
            ]);
            $save_dir = 'uploads/user';
            $filename = 'user_' . $userInfo->id . '.png';
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $file = $response->saveAs($save_dir, $filename);
                $userInfo->qr_image = DS . $save_dir . DS . $file;
            } else {
                exception('生成分享码失败');
            }
            $userInfo->save();
        }
        //我的消费金额
        $userInfo['consumption'] = Order::where('order_status', '>', '0')->where('user_id', $userInfo['id'])->sum('pay_fee');
        //我的团队消费金额
        $ids = ModelUser::where('pid', $userInfo['id'])->column('id');
        $userInfo['team_consumption'] = Order::where('order_status', '>', '0')->whereIn('user_id', $ids)->sum('pay_fee');
        //团队成员
        $userInfo['team_num'] = count($ids);
        //累计佣金
        $userInfo['total_commission'] = MoneyLog::where('class', 'commission')->where('type', '1')->whereIn('source_type', [200, 201, 202, 203])->where('user_id', $userInfo['id'])->sum('money');
        //待结算佣金
        $userInfo['frozen_commission'] = FrozenLog::where('user_id', $userInfo['id'])->sum('money');
        //已提金额
        $userInfo['withdrawal_commission'] = Withdrawal::where('user_id', $userInfo['id'])->where('state', '<>', '3')->sum('money');

        //服务区域判断
        $userInfo['accredit_num'] = Info::where('user_id', $userInfo->id)->where('accredit', 1)->count() ? true : false;
        //代理区域判断
        $userInfo['user_region_num'] = Region::where('user_id', $userInfo->id)->count() ? true : false;

        $this->success('', $userInfo);
    }
    /**
     * @Author LK
     * @date: 2023-11-01 
     * @ApiTitle (判断销售业绩显示隐藏)
     * @ApiMethod (GET)
     * @ApiParams (name="first_cate", type="integer", required=true, sample="", description="一级分类")
     * @ApiParams (name="two_cate", type="integer", required=true, sample="", description="二级分类")
     * @ApiParams (name="starttime", type="string", required=true, sample="", description="开始时间")
     * @ApiParams (name="start", type="string", required=true, sample="", description="开始时间")
     * @ApiParams (name="endtime", type="string", required=true, sample="", description="结束时间")
     * @ApiParams (name="end", type="string", required=true, sample="", description="结束时间")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function check_sales()
    {
        $params = request()->param();
        extract($params);
        $uid = $this->auth->id;
        $count = Info::where(['user_id' => $uid])->where('shareholder|investment', '>', 3)->count();
        $this->success('', $count);
    }

    /**
     * @Author LK
     * @date: 2023-11-01 
     * @ApiTitle (销售业绩)
     * @ApiMethod (GET)
     * @ApiParams (name="first_cate", type="integer", required=true, sample="", description="一级分类")
     * @ApiParams (name="two_cate", type="integer", required=true, sample="", description="二级分类")
     * @ApiParams (name="starttime", type="string", required=true, sample="", description="开始时间")
     * @ApiParams (name="start", type="string", required=true, sample="", description="开始时间")
     * @ApiParams (name="endtime", type="string", required=true, sample="", description="结束时间")
     * @ApiParams (name="end", type="string", required=true, sample="", description="结束时间")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function sales_performance()
    {
        $params = request()->param();
        extract($params);
        $uid = $this->auth->id;
        $info = Info::with(['upgradeinfo', 'investmentinfo'])->where(['user_id' => $uid, 'first_cate' => $first_cate, 'two_cate' => $two_cate])->where('shareholder|investment', '>', 3)->find();
        if ($info) {
            $wheres = $where = [];
            if (isset($starttime) && $starttime && isset($endtime) && $endtime) {
                $wheres['paytime'] = ['Between', [strtotime($starttime), strtotime($endtime . " 23:59:59")]];
            } else {
                if ($info->settlementtime > 0) {
                    $wheres['createtime'] = ['>', $info->settlementtime];
                } else {
                    if ($info->edittime > 0) {
                        $wheres['createtime'] = ['>', $info->edittime];
                    }
                }
            }
            if (isset($start) && $start && isset($end) && $end) {
                $where['createtime'] = ['Between', [strtotime($start), strtotime($end . " 23:59:59")]];
            } else {
                if ($info->settlementtime > 0) {
                    $where['createtime'] = ['>', $info->settlementtime];
                }
            }
            if ($info->shareholder > 3) {
                $info['shareholders'] = Log::where('user_id', $info->user_id)->where($wheres)->where('is_settle', 0)->where('p_shareholder', '>', 3)->where('shareholder', '<', $info['shareholder'])->where(['first_cate' => $first_cate, 'two_cate' => $two_cate])->field('IFNULL(sum(money),0) as amount,IFNULL(sum(goods_num),0) as num')->find();
            }
            if ($info->investment == 6) {
                $info['investments'] = Log::where('user_id', $info->user_id)->where($where)->where('is_settle', 0)->where('p_investment', 6)->where(['first_cate' => $first_cate, 'two_cate' => $two_cate])->field('IFNULL(sum(money),0) as amount,IFNULL(sum(goods_num),0) as num')->find();
            }
        }
        $this->success('', $info);
    }


    /**
     * @Author LK
     * @date: 2023-11-01 
     * @ApiTitle (销售明细)
     * @ApiMethod (GET)
     * @ApiParams (name="first_cate", type="integer", required=true, sample="", description="一级分类")
     * @ApiParams (name="two_cate", type="integer", required=true, sample="", description="二级分类")
     * @ApiParams (name="starttime", type="string", required=true, sample="", description="开始时间")
     * @ApiParams (name="endtime", type="string", required=true, sample="", description="结束时间")
     * @ApiParams (name="start", type="string", required=true, sample="", description="开始时间")
     * @ApiParams (name="end", type="string", required=true, sample="", description="结束时间")
     * @ApiParams (name="type", type="string", required=true, sample="", description="1=联创&股东2=联创")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function sales_detail()
    {
        $params = request()->param();
        extract($params);
        $uid = $this->auth->id;
        $wheres = $where = [];
        $info = Info::where(['user_id' => $uid, 'first_cate' => $first_cate, 'two_cate' => $two_cate])->where('shareholder|investment', '>', 3)->find();
        if ($info) {
            if (isset($starttime) && $starttime && isset($endtime) && $endtime) {
                $wheres['log.createtime'] = ['Between', [strtotime($starttime), strtotime($endtime . " 23:59:59")]];
            } else {
                if ($info->settlementtime > 0) {
                    $wheres['log.createtime'] = ['>', $info->settlementtime];
                } else {
                    if ($info->edittime > 0) {
                        $wheres['log.createtime'] = ['>', $info->edittime];
                    }
                }
            }
            if (isset($start) && $start && isset($end) && $end) {
                $where['log.createtime'] = ['Between', [strtotime($start), strtotime($end . " 23:59:59")]];
            } else {
                if ($info->settlementtime > 0) {
                    $where['log.createtime'] = ['>', $info->settlementtime];
                }
            }
            if ($type == 1) {
                $lists = Log::with(['goods', 'order'])->where('log.user_id', $info->user_id)->where($wheres)->where('log.is_settle', 0)->where('p_shareholder', '>', 3)->where('shareholder', '<', $info['shareholder'])->where(['log.first_cate' => $first_cate, 'log.two_cate' => $two_cate])->paginate();
            } else {
                $lists = Log::with(['goods', 'order'])->where('log.user_id', $info->user_id)->where($where)->where('log.is_settle', 0)->where('p_investment', 6)->where(['log.first_cate' => $first_cate, 'log.two_cate' => $two_cate])->paginate();
            }
        }
        $this->success('', $lists ?? '');
    }
    /**
     * @Author LK
     * @date: 2023-10-31 
     * @ApiTitle (直推成员)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function direct_member()
    {
        $uid = $this->auth->id;
        $field = "IFNULL(sum(l.money),0) as generateCommission,u.avatar,u.username,u.qr_code,u.id,u.invoice,u.qr_image";
        $users = ModelUser::alias('u')->join('user_money_log l', "u.id=l.uid and l.user_id={$uid}", 'left')->field($field)->group('u.id')->order('generateCommission desc')->where("pid", $uid)->paginate();
        $this->success('', $users);
    }
    /**
     * @Author LK
     * @ApiTitle (微信小程序登录)
     * @ApiMethod (POST)
     * @ApiParams (name="code", type="integer", required=true, sample="", description="登录code")
    //  * @ApiParams (name="phoneCode", type="integer", required=true, sample="", description="手机code")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function miniLogin()
    {
        $params = $this->request->param();
        extract($params);
        // 入参
        if (empty($code)) {
            $this->error('缺少必要参数!');
        }
        $result = [];
        try {
            $wechat = new Wechat('wxMiniProgram');
            $decryptSession = $wechat->code($code);
            if (!isset($decryptSession['session_key'])) {
                exception($decryptSession['errmsg']);
            }
            // if (empty($decryptSession['openid']) || empty($decryptSession['unionid'])) {
            //     exception('code错误,请重试!');
            // }
            if (empty($decryptSession['openid'])) {
                exception('code错误,请重试!');
            }
            if (isset($decryptSession['openid'])) {
                $where['openid'] = ['=', $decryptSession['openid']];
            }
            // if (isset($decryptSession['unionid'])) {
            //     $where['unionid'] = ['=', $decryptSession['unionid']];
            // }
            // $res = $wechat->getPhone($phoneCode);
            // if ($res['errcode'] == 0) {
            //     $phone = $res['phone_info'];
            //     $where['mobile'] = $phone['phoneNumber'];
            // } else {
            //     exception('失败:' . $res['errmsg']);
            // }
            // 分参
            $user = \app\common\model\User::get($where);
            if (!empty($user)) {
                if ($user->status != 'normal') {
                    exception(__('Account is locked'));
                }
                $result = $this->auth->direct($user->id, $decryptSession);
            } else {
                // $decryptSession['mobile'] = $phone['phoneNumber'];
                $result = $this->auth->oauthRegister($decryptSession);
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('授权登录成功', $this->auth->getUserInfo());
        } else {
            $this->error('授权登录失败了!' . $this->auth->getError());
        }
    }
    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     * @param string $code 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        $code = $this->request->post('code');
        if (!$mobile || !$captcha || !$code) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if ($captcha != '888888') {
            if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
                $this->error(__('Captcha is incorrect'));
            }
        }

        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            $wechat = new Wechat('wxMiniProgram');
            $decryptSession = $wechat->code($code);
            if (!isset($decryptSession['session_key'])) {
                exception($decryptSession['errmsg']);
            }
            if (!$decryptSession || !isset($decryptSession['openid'])) {
                exception('未获取到登录状态,请重试!');
            }
            if (empty($decryptSession['openid'])) {
                exception('code错误,请重试!');
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id, $decryptSession['openid']);
        } else {
            $this->error(__('Account not exist'));
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['token' => $this->auth->getToken()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 姓名
     * @param string $nickname 企业名称
     * @param string $qr_code 推荐码
     * @param string $bio    统一社会信用代码
     * @param string $mobile   手机号
     * @param string $code     验证码
     * @param string $province     省
     * @param string $city     市
     * @param string $area     区
     * @param string $address  地址
     */
    public function register()
    {
        $params = $this->request->post();
        extract($params);
        if (!$username || !$nickname) {
            $this->error(__('Invalid parameters'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if ($code != 888888) {
            $ret = Sms::check($mobile, $code, 'register');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
        }
        $user = ModelUser::get($this->auth->id);
        if ($user->pid > 0) {
            $this->error('已有推荐人');
        }
        if (!$qr_code) {
            $this->error('请输入推荐码');
        }
        $puser = ModelUser::get(['qr_code' => $qr_code]);
        if (!$puser) {
            $this->error('推荐人不存在');
        }

        $paren_ids = trim($puser->id . ',' . $puser['paren_ids'], ',');
        $extend = [
            'bio' => $bio,
            'pid' => $puser->id,
            'nickname' => $nickname,
            'username' => $username,
            'mobile' => $mobile,
            'name' => '微信用户',
            'province' => $province,
            'city' => $city,
            'area' => $area,
            'qr_code' =>  generate_invite_code(),
            'group_id' => 1,
            'paren_ids' => $paren_ids,
            'address' => $address,
            'region' => $province . '/' . $city . '/' . $area
        ];
        if (!$user->qr_image && $user->group_id > 0) {
            $wechat = new Wechat('wxMiniProgram');
            $scene = 'code=' . $user->qr_code;
            $response = $wechat->app_code($scene, [
                'page' => 'pages/login/register',
                'width' => 600,
                'check_path' => false,
            ]);
            $save_dir = 'uploads/user';
            $filename = 'user_' . $user->id . '.png';
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $file = $response->saveAs($save_dir, $filename);
                $extend['qr_image'] = DS . $save_dir . DS . $file;
            } else {
                exception('生成分享码失败');
            }
        }
        $ret = ModelUser::update($extend, ['id' => $this->auth->id]);
        if ($ret) {
            $this->success('修改成功');
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 姓名
     * @param string $name 昵称
     * @param string $nickname 公司名称
     * @param string $bio      统一社会信用代码
     * @param string $business_license      营业执照
     * @param string $auth_contract      授权合同
     * @param string $id_card_z      身份证-正
     * @param string $id_card_f      身份证-反
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $param = $this->request->param();
        extract($param);
        // if (!isset($business_license) || !$business_license) {
        //     $this->error('请上传营业执照');
        // }
        // if (!isset($auth_contract) || !$auth_contract) {
        //     $this->error('请上传授权合同');
        // }
        // if (!isset($id_card_z) || !$id_card_z) {
        //     $this->error('请上传身份证正面照');
        // }
        // if (!isset($id_card_f) || !$id_card_f) {
        //     $this->error('请上传身份证反面照');
        // }
        $user->business_license = $business_license;
        $user->auth_contract = $auth_contract;
        $user->id_card_z = $id_card_z;
        $user->id_card_f = $id_card_f;
        if ($auth_contract) {
            $user->auth_contract = $auth_contract;
        }
        if ($name) {
            $user->name = $name;
        }
        if ($username) {
            $user->username = $username;
        }
        if ($nickname) {
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }
    /**
     * @Author LK
     * @ApiTitle (添加/编辑银行卡)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=false, sample="", description="银行卡ID")
     * @ApiParams (name="cardholder", type="string", required=true, sample="", description="持卡人")
     * @ApiParams (name="bank_name", type="string", required=true, sample="", description="银行")
     * @ApiParams (name="outlets", type="string", required=true, sample="", description="网点")
     * @ApiParams (name="account", type="string", required=true, sample="", description="账号")
     * @ApiParams (name="id_card", type="string", required=true, sample="", description="身份证")
     * @ApiParams (name="type", type="string", required=true, sample="", description="类型:1=对公,2=个人")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function add_bank()
    {
        $param = request()->param();
        extract($param);
        $param['user_id'] = $this->auth->id;
        if (isset($id) && $id) {
            $bank = Bank::get($id);
            if (!$bank) {
                $this->error('银行卡不存在');
            }
            $res = $bank->allowField(true)->save($param);
        } else {
            $res = Bank::create($param, true);
        }
        if ($res) {
            $this->success('成功');
        }
        $this->error('失败');
    }

    /**
     * @Author LK
     * @ApiTitle (银行卡列表)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function bank_list()
    {
        $list = Bank::all(['user_id' => $this->auth->id]);
        $this->success('成功', $list);
    }

    /**
     * @Author LK
     * @ApiTitle (银行卡删除)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function del_bank()
    {
        $id = request()->param('id');
        if (!$id) {
            $this->error('参数错误');
        }
        $res = Bank::where('id', $id)->delete();
        if ($res) {
            $this->success('成功');
        }
        $this->error('失败');
    }

    /**
     * @Author LK
     * @ApiTitle (提现)
     * @ApiMethod (POST)
     * @ApiParams (name="money", type="integer", required=true, sample="", description="提现金额")
     * @ApiParams (name="type", type="integer", required=true, sample="", description="1=微信提现,2=支付宝,3=银行卡")
     * @ApiParams (name="image", type="string", required=true, sample="", description="发票")
     * @ApiParams (name="account", type="string", required=false, sample="", description="账号")
     * @ApiParams (name="bank_id", type="string", required=false, sample="", description="银行卡id")
     * @ApiParams (name="mark", type="string", required=false, sample="", description="备注")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function withdrawal()
    {
        $post = $this->request->post();
        $user = ModelUser::get($this->auth->id);
        $post['commission'] = $user['commission'];
        extract($post);
        if (!isset($user['business_license']) || !$user['business_license']) {
            $this->error('请上传营业执照');
        }
        if (!isset($user['id_card_z']) || !$user['id_card_z']) {
            $this->error('请上传身份证正面照');
        }
        if (!isset($user['id_card_f']) || !$user['id_card_f']) {
            $this->error('请上传身份证反面照');
        }
        $validate = validate('user.Withdrawal'); //使用助手函数
        if ($type == 1) {
            $scene = 'wechat';
        } elseif ($type == 2) {
            $scene = 'alipay';
        } elseif ($type == 3) {
            $scene = 'bank';
        }
        $result = $validate->scene($scene)->check($post);
        if (!$result) {
            $this->error($validate->getError());
        }
        $withdrawal_commission = config('site.withdrawal_commission');
        if ($withdrawal_commission > 0 && $withdrawal_commission <= 100) {
            $withdrawal_commission_fee = bcdiv($withdrawal_commission, 100, 2);
            $handling_charge = bcmul($money, $withdrawal_commission_fee, 2);
        } else {
            $handling_charge = 0;
        }
        if ($type == 3) {
            $bank = Bank::get($bank_id);
            $post['account'] = $bank->account;
        }
        $post['sn'] = sn('user_withdrawal', 'sn', 'TX');
        $post['user_id'] = $user['id'];
        $post['image'] = $image;
        $post['handling_charge'] = $handling_charge;
        $post['amount_received'] = bcsub($money, $handling_charge, 0);
        $post['type'] = $type;
        Db::startTrans();
        try {
            $tx = new Withdrawal($post);
            $tx->allowField(true)->save();
            MoneyLog::income($user['id'], $money, 2, 300, $post['sn']);
            Db::commit();
        } catch (\Exception $th) {
            Db::rollback();
            $this->error($th->getMessage());
        }
        $this->success('申请成功');
    }
    /**
     * @Author LK
     * @ApiTitle (用户提现记录)
     * @ApiMethod (get)
     * @ApiParams (name="state", type="integer", required=true, sample="", description="1=提现中,2=提现成功,3=提现失败")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function withdrawalLog()
    {
        $get = request()->get();
        extract($get);
        $withdrawal = new Withdrawal;
        if ($state != 'all') {
            $withdrawal->where('state', $state);
        }
        $withdrawal->where('user_id', $this->auth->id);
        $withdrawal->order('createtime desc');
        $list = $withdrawal->field("*,FROM_UNIXTIME(createtime,'%Y-%m-%d') as create_time")->paginate(10);
        $this->success('', $list);
    }

    /**
     * @Author LK
     * @date: 2023-10-31 
     * @ApiTitle (消费记录)
     * @ApiMethod (GET)
     * @ApiParams (name="starttime", type="string", required=true, sample="", description="开始时间")
     * @ApiParams (name="endtime", type="string", required=true, sample="", description="结束")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function consumption_record()
    {
        $param = request()->param();
        extract($param);
        $order = new Order;
        if (isset($starttime) && $starttime && isset($endtime) && $endtime) {
            $order->whereBetween('paytime', [strtotime($starttime), strtotime($endtime)]);
        }
        $lists = $order->with(['goods'])->where('user_id', $this->auth->id)->where('order_status', '>', '0')->order('id desc')->paginate();
        $this->success('', $lists);
    }
    /**
     * @Author LK
     * @date: 2023-10-31 
     * @ApiTitle (佣金明细)
     * @ApiMethod (GET)
     * @ApiParams (name="type", type="string", required=true, sample="", description="1=收入,2=支出")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function commission_detail()
    {
        $param = request()->param();
        extract($param);
        $model = new MoneyLog();
        if (isset($type) && $type) {
            $model->where('type', $type);
        }
        $lists = $model->where('user_id', $this->auth->id)->where('class', 'commission')->whereIn('source_type', MoneyLog::commission_change)->order('id desc')->paginate();
        foreach ($lists as $k => $v) {
            $v->order = Order::get(['sn' => $v->order_sn], ['goods']);
        }
        $this->success('', $lists);
    }
    /**
     * @Author LK
     * @date: 2023-11-02 
     * @ApiTitle (保存发票信息)
     * @ApiMethod (POST)
     * @ApiParams (name="class", type="string", required=true, sample="", description="发票类型:1=专用发票,2=普通发票")
     * @ApiParams (name="rise", type="string", required=true, sample="", description="抬头类型:1=企业,2=个人")
     * @ApiParams (name="title", type="string", required=true, sample="", description="公司名称")
     * @ApiParams (name="identification", type="string", required=true, sample="", description="纳税人识别号")
     * @ApiParams (name="address", type="string", required=true, sample="", description="地址")
     * @ApiParams (name="phone", type="string", required=true, sample="", description="联系电话")
     * @ApiParams (name="account", type="string", required=true, sample="", description="银行账号")
     * @ApiParams (name="bank", type="string", required=true, sample="", description="开户行")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function add_invoice_information()
    {
        $param = request()->param();
        extract($param);
        $user = ModelUser::get($this->auth->id);
        $user->invoice = json_encode($param);
        $user->save();
        $this->success('保存成功');
    }
    /**
     * @Author LK
     * @date: 2023-11-07 
     * @ApiTitle (保存授权合同)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="images", type="string", required=true, sample="", description="授权合同")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function upImages()
    {
        $param = request()->param();
        extract($param);
        $info = Info::get($id);
        if (isset($images) && $images) {
            $info->images = $images;
        }
        $info->save();
        $this->success('保存成功');
    }
    /**
     * @Author LK
     * @date: 2023-11-07 
     * @ApiTitle (代理收货区域授权)
     * @ApiMethod (get)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function agent_area_auth()
    {
        $param = request()->param();
        extract($param);
        $lists = Region::all(['user_id' => $this->auth->id]);
        $this->success('', $lists);
    }

    /**
     * @Author LK
     * @date: 2023-11-07 
     * @ApiTitle (服务商收货区域授权)
     * @ApiMethod (get)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function service_area_auth()
    {
        $param = request()->param();
        extract($param);
        $lists = info::get(['user_id' => $this->auth->id, 'accredit' => 1], ['firstcate', 'twocate']);
        $this->success('', $lists);
    }

    /**
     * @Author LK
     * @date: 2023-11-07 
     * @ApiTitle (个人业绩明细)
     * @ApiMethod (get)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function performance_detail()
    {
        $param = request()->param();
        extract($param);
        $idss = Order::where('order_status', '>', '0')->where('user_id', $this->auth->id)->column('id');
        $list =  Goods::with(['order'])->whereIn('order_id', $idss)->order('id desc')->paginate();
        $this->success('', $list);
    }

    /**
     * @Author LK
     * @date: 2023-11-07 
     * @ApiTitle (直推业绩明细)
     * @ApiMethod (get)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function direct_thrust_performance_detail()
    {
        $param = request()->param();
        extract($param);
        $uids = ModelUser::where('pid', $this->auth->id)->column('id');
        $idss = Order::where('order_status', '>', '0')->whereIn('user_id', $uids)->column('id');
        $list =  Goods::with(['order'])->whereIn('order_id', $idss)->order('id desc')->paginate();
        $this->success('', $list);
    }
}
